package com.apestech.formwork.condition;

import com.apestech.api.condition.ConditionExec;
import com.apestech.api.exp.XLSTable;
import com.apestech.api.tables.modul.SeqField;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.pinyin.PinyinConverter;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.util.callback.SpiltStrCallback;
import com.apestech.framework.xml.ReadXmlNodeInter;
import com.apestech.framework.xml.condition.modul.*;
import com.apestech.framework.xml.plugin.XmlPaste;
import com.apestech.framework.xml.table.modul.Tables;
import org.dom4j.Element;

import java.io.File;
import java.util.ArrayList;

/**
 * @author hup
 * @create 2019-01-25-17:37
 */
public class ConditionUtil extends StringUtil{

    private static JSONObject dimensionMap=new JSONObject();
    private static JSONObject dimensionDb=new JSONObject();
    private static JSONObject condition=new JSONObject();
    private static JSONObject conditionStrategy=new JSONObject();
    private static JSONObject account=new JSONObject();
    private static JSONObject tables=new JSONObject();
    private static JSONObject report=new JSONObject();
    private static JSONObject xlss=new JSONObject();
    private static ArrayList<SeqField> seqlist=new ArrayList<SeqField>();

    //条件策略相关XML结点数据读取初始化
    public static void getAllCondition(SqlSession session) throws Exception {
        /*
        xml调用：直接ID+init， path+id， file+id
        */
        System.out.println("初始化条件策略列表");
        String path=LocalVariable.getRootDir()+"condition"+File.separator;
        if(FileUtil.isFileExist(path+session.getTheme()+File.separator)){
            path=path+session.getTheme()+File.separator;
        }
        XmlPaste xmlp=new XmlPaste(session);
        xmlp.getXmlQuery().setFileDir(path);
        ArrayList<String> nlist=new ArrayList<String>();
        nlist.add("conditionDef");
        nlist.add("conditionStrategyDef");
        nlist.add("accountDef");
        nlist.add("tables");
        nlist.add("report");
        nlist.add("xlsRead");
        xmlp.getXmlQuery().getXmlFileNode(nlist, new ReadXmlNodeInter(){
            @Override
            public void ReadNode(Element root, Element node, String nodename) throws Exception {
                String id=node.attributeValue("id");
                try{
                    xmlp.expain(root, node);
                }catch(Exception e){
                    String msg=e.getMessage();
                    if(msg!=null && (msg.indexOf("维度字段id")>=0 || msg.indexOf("表或视图不存在")>=0)){
                        System.out.println("策略ID["+id+"]"+e.getMessage());
                        return;
                    } else {
                        throw e;
                    }
                }
                switch (nodename){
                    case "conditionDef":{
                        Condition conditon=xmlp.getCondition();
                        writeCondition(session, id, conditon.getName());
                        if(conditon.getDimension().size()>0){
                            conditon.getTables();
                            condition.put(id,conditon);
                        }
                        break;
                    }
                    case "conditionStrategyDef":{
                        ConditionStrategy conStrategy=xmlp.getConditionStrategy();
                        conditionStrategy.put(id,conStrategy);
                        break;
                    }
                    case "accountDef":{
                        account.put(id,xmlp.getAccount());
                        break;
                    }
                    case "tables":{
                        tables.put(id,xmlp.getTable());
                        break;
                    }
                    case "report":{
                        report.put(id,xmlp.getReport());
                        break;
                    }
                    case "xlsRead":{
                        xlss.put(id, new XLSTable(xmlp.getSingleResult()));
                        break;
                    }
                };
            }
        });
    }

    private static void writeCondition(SqlSession session, String id, String name) throws Exception {
        String sql="SELECT NAME, LAST_UPDATED_STAMP FROM EXE_CONDITION WHERE 1=1 AND ID=#{ID} ";
        JSONObject param=new JSONObject();
        param.put("ID", id);
        param.put("NAME", name);
        param.put("CREATE_DATE","SYSDATE");
        param.put("LAST_UPDATED_STAMP","SYSDATE");
        param.put("autoCompletion","0");
        param.put("printSql","false");
        session.getForResultSet().sql(sql, param, new QueryCallBackHandler(){
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                if(!rs.next()){
                    session.getForUpdate().insertTable("EXE_CONDITION", param);
                } else {
                    if(!rs.getString("NAME").equals(param.getString("NAME"))){
                        param.put("LAST_UPDATED_STAMP_OLD",rs.getString("LAST_UPDATED_STAMP"));
                        session.getForUpdate().updateTable("EXE_CONDITION", param);
                    }
                }
            }
        });
    }

    //获取全部Condition数据，用于功能联想控件取数
    public static JSONArray getCondition(SqlSession session) throws Exception {
        return getCondition(session, null, null, false);
    }

    //获取全部Condition数据，用于功能联想控件取数，适用于输入关键字查找
    public static JSONArray getCondition(SqlSession session, String key, JSONObject param) throws Exception {
        return getCondition(session, key, param, false);
    }

    //获取已用的Condition数据，用于功能联想控件取数
    public static JSONArray getConditionUsed(SqlSession session) throws Exception {
        return getCondition(session, null, null, true);
    }

    //获取已用的Condition数据，用于功能联想控件取数，适用于输入关键字查找
    public static JSONArray getConditionUsed(SqlSession session, String key, JSONObject param) throws Exception {
        return getCondition(session, key, param, true);
    }

    private static JSONArray getCondition(SqlSession session, String key, JSONObject param, boolean isUsed) throws Exception {
        if(condition.size()==0) getAllCondition(session);
        JSONArray list=new JSONArray();
        ArrayList<String> klist=condition.getKeylist();
        if(key!=null){
            key=key.toLowerCase();
        }
        String id=param.getString("ID");
        String name=param.getString("NAME");
        if(id!=null){
            id=id.toLowerCase();
        }
        if(name!=null){
            name=name.toLowerCase();
        }
        int len=klist.size();
        for(int i=0; i<len; i++){
            Condition con= (Condition) condition.get(klist.get(i));
            if(!con.isInvalid()){
                String py=new PinyinConverter().getPinyinAbbr(con.getName()).toLowerCase();
                String cid=con.getId().toLowerCase();
                String cname=con.getName().toLowerCase();
                boolean flag=true;
                if(id==null && name==null){
                    flag=(key==null || (cid.indexOf(key)>=0 || (cname.toLowerCase().indexOf(key)>=0 || (py.indexOf(key)>=0) )));
                } else {
                    if(id!=null){
                        flag=flag && cid.indexOf(id)>=0;
                    }
                    if(name!=null){
                        flag=flag && (cname.indexOf(name)>=0 || py.indexOf(name)>=0);
                    }
                }
                if(isUsed && flag) {
                    flag=session.tableExists(con.getTables().get(0).getMasterTable());
                }
                if(flag){
                    //EXE_CONDITION
                    JSONObject m=new JSONObject();
                    m.put("id", con.getId());
                    m.put("ID", con.getId());
                    m.put("NAME", con.getName());
                    m.put("name", m.getString("NAME"));
                    m.put("NAME_PY", py);
//                    if(param!=null) flag=(qryMap(param, m)!=null);
                    if(flag) list.add(m);
                }
            }
        }
        return list;
    }

    private static JSONObject qryMap(JSONObject input, JSONObject output){
        if(input==null) return output;
        ArrayList<String> list=input.getKeylist();
        int len=list.size();
        for(int i=0; i<len; i++){
            String k=list.get(i);
            if(output.getString(k).indexOf(input.getString(k))<0){
                return null;
            }
        }
        return output;
    }


    public static JSONArray getConditionStrategy(SqlSession session, String key, String id, String name) throws Exception {
        if(condition.size()==0) getAllCondition(session);
        if(key!=null) {
            key=key.toLowerCase();
        }
        if(id!=null) {
            id=id.toLowerCase();
        }
        if(name!=null) {
            name=name.toLowerCase();
        }
        JSONArray list=new JSONArray();
        ArrayList<String> klist=conditionStrategy.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            ConditionStrategy con= (ConditionStrategy) conditionStrategy.get(klist.get(i));
            String py=new PinyinConverter().getPinyinAbbr(con.getName()).toLowerCase();
            boolean flag=true;
            String cid=con.getId().toLowerCase();
            String cname=con.getName().toLowerCase();
            if(id==null && name==null){
                flag=(key==null || (cid.indexOf(key)>=0 || (cname.indexOf(key)>=0 || (py.indexOf(key)>=0) )));
            } else {
                if(id!=null){
                    flag=cid.indexOf(id)>=0;
                }
                if(name!=null){
                    flag=flag && (cname.indexOf(name)>=0 || (py.indexOf(name)>=0));
                }
            }
            if(flag){
                JSONObject m=new JSONObject();
                m.put("id", con.getId());
                m.put("ID", con.getId());
                m.put("NAME", con.getName());
                m.put("name", m.getString("NAME"));
                m.put("NAME_PY", py);
                if(flag) list.add(m);
            }
        }
        return list;
    }

    //获取某个ID下的Condition模型
    public static Condition getCondition(String id, SqlSession session) throws Exception {
        if(condition.get(id)==null){
            XmlPaste xml=new XmlPaste(id, "conditionDef", session);
            xml.expain();
            condition.put(id, xml.getCondition());
        }
        Condition con=(Condition) new Condition((Condition) condition.get(id));
        if(con!=null){
            con.setSession(session);
        }
        return con;
    }

    //获取某个ID下的ConditionStrategy模型
    public static ConditionStrategy getConditionStrategy(String id, SqlSession session) throws Exception {
        if(conditionStrategy.get(id)==null){
            XmlPaste xml=new XmlPaste(id, "conditionStrategyDef", session);
            xml.expain();
            conditionStrategy.put(id, xml.getConditionStrategy());
        }
        ConditionStrategy con=new ConditionStrategy((ConditionStrategy) conditionStrategy.get(id));
        return con;
    }

    public static Account getAccount(String id, SqlSession session) throws Exception {
        if(account.get(id)==null){
            XmlPaste xml=new XmlPaste(id, "accountDef", session);
            xml.expain();
            account.put(id, xml.getAccount());
        }
        Account acc=(Account) account.get(id);
        acc.setSession(session);
        return acc;
    }

    public static Tables getTables(String id, SqlSession session) throws Exception {
        if(tables.get(id)==null){
            XmlPaste xml=new XmlPaste(id, "tables", session);
            xml.expain();
            tables.put(id, xml.getTable());
        }
        return (Tables) tables.get(id);
    }

    public static Tables getTables(String id) throws Exception {
        if(tables.get(id)==null){
            return null;
        }
        return (Tables) tables.get(id);
    }

    public static Report getReport(String id, SqlSession session) throws Exception {
        if(report.get(id)==null){
            XmlPaste xml=new XmlPaste(id, "report", session);
            xml.expain();
            report.put(id, xml.getReport());
        }
        return (Report) report.get(id);
    }

    public static void getAllDimensionDef(SqlSession session) throws Exception {
        dimensionMap = new JSONObject();
        System.out.println("初始化维度列表");
        String sql = "<rule from=\"EXE_DIMENSION\" autoCompletion=\"0\" />" +
                " SELECT ID,NAME,FIELD FROM EXE_DIMENSION ORDER BY FIELD,ID ";
        JSONObject p=new JSONObject();
        p.put("printSql","false");
        session.getForResultSet().sql(sql, p, new QueryCallBackHandler() {
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                JSONObject m = new JSONObject();
                while (rs.next()) {
                    String field = rs.getString("FIELD");
                    String id = rs.getString("ID");
                    if (m.get(field) == null) {  //换成判断个数及字段内容方式算法
                        try{
                            String name = getDimensionName(rs.getString("NAME"));
                            setDimensionMap(id, name, field, session);
                            m.put(field,"1");
                        } catch (Exception e){
                            String msg=e.getMessage();
                            if(msg.indexOf("维度字段id")>=0 || msg.indexOf("表或视图不存在")>=0){
                                System.out.println("维度ID["+id+"]"+e.getMessage());
                            } else {
                                throw e;
                            }
                        }
                    }
                }
            }
        });
    }

    public static void setDimensionMap(String id, String name, String fields, SqlSession session) throws Exception {
        if(dimensionMap.get(id)==null){
            Dimension d = new Dimension(session);
            JSONObject map = new JSONObject();
            map.put("fields", fields);
            d.addField(id, name, fields);
            d.getFieldlist_ini(true);
            dimensionMap.put(id, d);
        }
    }

    public static Dimension getDimension(String id, SqlSession session){
        Dimension dim=(Dimension) dimensionMap.get(id);
        dim.setSession(session);
        return dim;
    }

    public static JSONArray getDimension(SqlSession session, String key, JSONObject param) throws Exception {
        ArrayList<String> klist=dimensionMap.getKeylist();
        JSONArray qlist=new JSONArray();
        int len=klist.size();
        for(int i=0; i<len; i++){
            Dimension d= (Dimension) dimensionMap.get(klist.get(i));
            JSONObject m=getDimensionMap(session, d, key, param, false, null);
            if(m!=null) qlist.add(m);
        }
        return qlist;
    }

    private static JSONObject getDimensionMap(SqlSession session, Dimension d, String key, JSONObject param, boolean isUsed, String tabname) throws Exception {
        String py=new PinyinConverter().getPinyinAbbr(d.getName());
        boolean flag=((key==null)||(d.getId().toLowerCase().indexOf(key)>=0 || d.getName().toLowerCase().indexOf(key)>=0 || py.toLowerCase().indexOf(key)>=0 ));
        if(isUsed && flag) {
            flag=session.tableExists(tabname);
        }
        if(flag){
            JSONObject m=new JSONObject();
            m.put("id", d.getId());
            m.put("ID", d.getId());
            m.put("FIELD", d.getFieldKey().replace(",","/"));
            m.put("NAME", getDimensionName(d.getName()));
            m.put("name", m.getString("NAME"));
            m.put("NAME_PY", py);
            if(param!=null) flag=(qryMap(param, m)!=null);
            return m;
        }
        return null;
    }

    public static JSONArray qryDimension(SqlSession session, JSONObject input) throws Exception {
        JSONArray qlist=new JSONArray();
        getAllDimensionDef(session);
        ArrayList<String> klist=dimensionMap.getKeylist();
        String id=input.getString("ID");
        String name=input.getString("NAME");
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Dimension d= (Dimension) dimensionMap.get(k);
            boolean flag=true;
            if(id!=null){
                if(!id.equals(d.getId())) flag=false;
            }
            if(flag && name!=null){
                if(d.getName().indexOf(name)<0) flag=false;
            }
            if(flag){
                JSONObject m=new JSONObject();
                m.put("ID", d.getId());
                m.put("NAME", getDimensionName(d.getName()));
                m.put("FIELD", d.getFieldKey().replace(",","/"));
                m.put("FIELD_NAME", d.getFieldKeyName());
                qlist.add(m);
            }
        }
        return qlist;
    }

    private static String getDimensionName(String name) throws Exception {
        String dname=name;
        final String[] s = {""};
        if(dname.indexOf("(")>0 && dname.indexOf(")")>0 && dname.indexOf(":")>0 ){
            execSplitStr(dname,"/", new SpiltStrCallback(){
                @Override
                public void exec(String id) throws Exception {
                    if(!"".equals(s[0])){
                        s[0]=s[0]+"/";
                    }
                    if(id.indexOf("(")>0 && id.indexOf(")")>0 && id.indexOf(":")>0 ){
                        s[0] = s[0] +getSpiltId(id);
                    } else {
                        s[0] = s[0] +id;
                    }
                }
            });
            return s[0];
        } else {
            return name;
        }
    }

    public static JSONObject getDimensionMap() {
        if(dimensionMap==null) dimensionMap=new JSONObject();
        return dimensionMap;
    }

    public static JSONObject getDimensionDb() {
        return dimensionDb;
    }


    public class BillTable {
        private int order;
        private ArrayList<String> fields;
        private String oper;  //bill, all
        private boolean alter;
        private Object seqTime;
        public BillTable(int order, ArrayList<String> fields, String oper, boolean alter, Object seqTime){
            this.order=order;
            this.fields=fields;
            this.oper=oper;
            this.alter=alter;
            this.seqTime=seqTime;
        }

        public int getOrder() {
            return order;
        }

        public ArrayList<String> getFields() {
            return fields;
        }

        public String getOper() {
            return oper;
        }

        public boolean isAlter() {
            return alter;
        }

        public Object getSeqTime() {
            return seqTime;
        }
    }

    public BillTable getBillOrder(String tableName, Account account, ArrayList<String> fields, SqlSession session) throws Exception {
        ArrayList<String> addfields=new ArrayList<String>();
        int len=fields.size();
        int j=0;
        JSONObject map=new JSONObject();
        map.put("ID", account.getId());
        map.put("TABLE_ID", tableName);
        map.put("TABLE_NAME", tableName);
        JSONArray qlist=session.getForJSON().query("SELECT NUM FROM EXE_ACCOUNT_BILL WHERE TABLE_ID=#{TABLE_ID} AND ID=#{ID} ", map);
        if(qlist.size()>0) return new BillTable(qlist.get(0).getInteger("NUM"), fields,null, false, null);
        int num=0;
        qlist=session.getForJSON().query("SELECT NUM,LAST_UPDATED_STAMP FROM EXE_ACCOUNT_BILL_SEQ WHERE TABLE_ID=#{TABLE_ID} ", map);
        Object time=null;
        if(qlist.size()>0){
            num=qlist.get(0).getInteger("NUM");
            time=qlist.get(0).get("LAST_UPDATED_STAMP");
        }
        Table table=session.getDictTable(tableName+"_"+num);
        if(table==null) return new BillTable(num, fields, "all", false, time);
        for(int i=0; i<len; i++){
            String key=fields.get(i);
            JSONObject output=account.getStep().getAllOutputDef();
            ConditionStrategy.Field field= (ConditionStrategy.Field) output.get(key);
            if(field!=null){
                String sid=field.getTarget();
                JSONObject f= (JSONObject) account.getConditon().getAllField().get(sid);
                if(!f.getString("type").equals(table.getDbType(key)))
                    throw new Exception("当前字段["+key+"]已有定义过，新引用字段对应type不同，建议通过改名解决！");
                String fname=table.getRemarks(key);
                if(!f.getString("comment").equals(fname) && !key.equals(fname))
                    throw new Exception("当前字段["+key+"]已有定义过，新引用字段对应中文含义不同，建议通过改名解决！");
                j++;
                addfields.add(key);
            }
        }
        if((table.getField().size()+num-j)>30) return new BillTable(num+1, addfields, "all", false, time);
        return new BillTable(num, addfields, "bill", true, time);
    }

    public void getAllTables(Tables tables, SqlSession session) throws Exception {
        ArrayList<String> klist=tables.getRelat().getOrderKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String tid=klist.get(i);
            String tableName=tables.getTabName(tid);
            JSONObject map=new JSONObject();
            map.put("TABLE_ID", tableName);
            JSONArray qlist=session.getForJSON().query("SELECT NUM,LAST_UPDATED_STAMP FROM EXE_ACCOUNT_BILL_SEQ WHERE TABLE_ID=#{TABLE_ID} ", map);
            int order=-1;
            if(qlist.size()>0) order=qlist.get(0).getInteger("NUM");
            if(order>=0){
                for(int t=0; t<=order; t++){
                    String mid=tableName+"_"+t;
                    tables.addMasterTab(mid, mid, tid, tid);
                }
            }
        }
    }

    public static ArrayList<SeqField> getSeqlist() {
        return seqlist;
    }

    public static void createTable(SqlSession session) throws Exception {
        ArrayList<String> klist=tables.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            Tables tab= (Tables) tables.get(klist.get(i));
            if(!session.tableExists(tab.getMasterTable())){
                session.getForDDL().createTable(tab);
            }
        }
    }

    public static void createTable(String tabId, SqlSession session) throws Exception {
        Tables tab= (Tables) tables.get(tabId);
        if(tab==null) return;
        if(!session.tableExists(tab.getMasterTable())){
            session.getForDDL().createTable(tab);
        }
    }

    public static void reCreateTable(SqlSession session) throws Exception {
        ArrayList<String> klist=tables.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            Tables tab= (Tables) tables.get(klist.get(i));
            session.getForDDL().dropTables(tab);
            session.getForDDL().createTable(tab);
        }
    }

    public static void createConditionTable(SqlSession session, boolean drop) throws Exception {
        ArrayList<String> klist=condition.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            Condition con= (Condition) condition.get(klist.get(i));
            ConditionExec exec=new ConditionExec(session, con.getId());
            exec.createTable(drop);
        }
    }

    public static void createConditionTable(String conditionId, SqlSession session, boolean drop) throws Exception {
        Condition con= (Condition) condition.get(conditionId);
        ConditionExec exec=new ConditionExec(session, con.getId());
        exec.createTable(drop);
    }

    public static void addCreateConditionTable(SqlSession session) throws Exception {
        ArrayList<String> klist=condition.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            Condition con= (Condition) condition.get(klist.get(i));
            ConditionExec exec=new ConditionExec(session, con.getId());
            exec.addCreateTable();
        }
    }

    public static XLSTable getXls(String id) throws Exception {
        return (XLSTable) xlss.get(id);
    }

    public static ArrayList<String> getFileTypeIdList(SqlSession session, String xmlfile, String type) throws Exception {
        ArrayList<String> idlist=new ArrayList<String>();
        XmlPaste xmlp=new XmlPaste(session);
        xmlp.getXmlQuery().setFileDir(xmlfile);
        ArrayList<String> nlist=new ArrayList<String>();
        nlist.add(type);
        xmlp.getXmlQuery().getXmlFileNode(nlist, new ReadXmlNodeInter(){
            @Override
            public void ReadNode(Element root, Element node, String nodename) throws Exception {
                String id=node.attributeValue("id");
                if(nodename.equals(type)){
                    idlist.add(id);
                }
            }
        });
        return idlist;
    }

    public static JSONArray getConditionFromDb(SqlSession session, JSONObject input) throws Exception{
        String sql="SELECT A.ID, A.NAME FROM EXE_CONDITION A WHERE 1 = 1\n";
        String posId=input.getString("POSTID");
        String sysform=input.getString("sysform");
        String key=input.getString("key");
        String id=input.getString("ID");
        String name=input.getString("NAME");
        input.remove("key");
        if(key!=null){
            key=key.toUpperCase();
        }
        input.put("KEY", key);
        if(id!=null){
            id=id.toUpperCase();
        }
        input.put("ID", id);
        if(name!=null){
            name=name.toUpperCase();
        }
        input.put("NAME", name);
        if(key!=null){
            sql=sql+" AND (UPPER(A.ID) LIKE '%'||#{KEY}||'%' OR UPPER(A.NAME) LIKE '%'||#{KEY}||'%' OR UPPER(A.INITIALS) LIKE '%'||#{KEY}||'%') \n";
        }
        if(id!=null){
            sql=sql+" AND UPPER(A.ID) LIKE '%'||#{ID}||'%' \n";
        }
        if(name!=null){
            sql=sql+" AND (UPPER(A.NAME) LIKE '%'||#{NAME}||'%' OR UPPER(A.INITIALS) LIKE '%'||#{NAME}||'%') \n";
        }
        if(posId!=null){
            sql=sql+"   AND EXISTS (SELECT 1 FROM AUT_CONDITION X, AUT_ROLE_POSTS Y\n" +
                    "         WHERE X.ROLE_ID = Y.ROLE_ID\n" +
                    "           AND X.CONDITION_ID = A.ID\n" +
                    "           AND Y.POST_ID = #{POSTID} ";
            if("zd_a".equals(sysform)){
                sql=sql+"           AND (X.AUT_CREATE = 1 OR X.AUT_APPROVE = 1 OR X.AUT_STOP = 1)";
            } else if("zd".equals(sysform)){
                sql=sql+"           AND (X.AUT_CREATE = 1)";
            } else if("cx".equals(sysform)){
                sql=sql+"           AND (X.AUT_QRY_EXEC = 1)";
            } else if("zz".equals(sysform)){
                sql=sql+"           AND (X.AUT_STOP = 1)";
            }
            sql=sql+")";
        }
        input.remove("page");
        input.remove("size");
        input.put("autoCompletion","0");
        return session.getForJSON().query(sql, input);
    }

    public static JSONObject getConditionRole(SqlSession session, JSONObject input) throws Exception {
        String sql="SELECT X.AUT_CREATE, X.AUT_APPROVE, X.AUT_STOP, X.AUT_QRY_EXEC\n" +
                "          FROM AUT_CONDITION X, AUT_ROLE_POSTS Y\n" +
                "         WHERE X.ROLE_ID = Y.ROLE_ID\n" +
                "           AND X.CONDITION_ID = #{ID} \n" +
                "           AND Y.POST_ID = #{POSTID}  ";
        input.put("autoCompletion","0");
        JSONArray list=session.getForJSON().query(sql, input);
        if(list==null || list.size()==0){
            return null;
        } else {
            return list.get(0);
        }
    }
}
